package my.diplom.web.ajax;

import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.ValidationUtils;
import org.springframework.util.StringUtils;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import my.diplom.entity.*;
import my.diplom.dao.service.*;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: gb
 * Date: 13.08.2009
 * Time: 1:33:56
 * To change this template use File | Settings | File Templates.
 */
public class AjaxController extends MultiActionController {

    private static final Logger log = Logger.getLogger(AjaxController.class);

    private CategoryService categoryService;
    private StatusService statusService;
    private ApplicationService applicationService;
    private ProjectService projectService;
    private UserService userService;
    private ResourceService resourceService;
    private HostService hostService;


    public void setResourceService(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    public void setHostService(HostService hostService) {
        this.hostService = hostService;
    }

    public void setCategoryService(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    public void setStatusService(StatusService statusService) {
        this.statusService = statusService;
    }

    public void setApplicationService(ApplicationService applicationService) {
        this.applicationService = applicationService;
    }

    public void setProjectService(ProjectService projectService) {
        this.projectService = projectService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    public ModelAndView getApplicationsByCategory(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String category = request.getParameter("curCat");
        HashMap<String, Object> model = new HashMap<String, Object>();
        Set<Application> applications = categoryService.getById(Long.parseLong(category), true).getActiveApplications();
        model.put("applications", applications);
        model.put("method", "getApplicationsByCategory");
        log.debug("new date = " + new Date());
        return new ModelAndView("ajax_foo", model);
    }

    public ModelAndView newApplication(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String error = "";
        String appName = request.getParameter("appName");
        Long categoryId = Long.parseLong(request.getParameter("categoryId"));
        String description = request.getParameter("description");
        String status = request.getParameter("status");
        if (appName == null || appName.trim().length() < 1)
            error += "appName:Name is required;";
        if (status == null || status.trim().length() < 1 || status.equals("undefined"))
            error += "status:Status is required;";
        if (error.length() == 0) {
            Application application = new Application();
            if (request.getParameter("appId") != "")
                application.setApplicationId(Long.parseLong(request.getParameter("appId")));
            application.setApplicationName(appName);
            application.setDescription(description);
            application.setCategory(categoryService.getById(categoryId));
            application.setStatus(statusService.getByName(status));
            applicationService.update(application);
        }
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("method", "newApplication");
        model.put("error", error);
        return new ModelAndView("ajax_foo", model);
    }

    public ModelAndView deleteApplication(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String error = "";
        try {
            Long applicationId = Long.parseLong(request.getParameter("applicationId"));
            Application application = applicationService.getById(applicationId);
            applicationService.delete(application);
        } catch (Exception e) {
            e.printStackTrace();
            error = "Can't delete application";
        }
        HashMap<String, Object> model = new HashMap<String, Object>();
        model.put("method", "deleteApplication");
        model.put("error", error);
        return new ModelAndView("ajax_foo", model);
    }


    public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String error = "";
        HashMap<String, Object> model = new HashMap<String, Object>();
        try {
            Long userId = Long.parseLong(request.getParameter("userId"));
            User user = userService.getById(userId);
            Long projectId = Long.parseLong(request.getParameter("projectId"));
            Project project = projectService.getById(projectId, true);

            if (!project.getUsers().contains(user)) {
                project.addUser(user);
                projectService.update(project);
                model.put("user", user);
            } else {
                error = "Error:User already exists in this project";
            }
        } catch (Exception e) {
            e.printStackTrace();
            error = "Error:Can't add user";
        }

        model.put("method", "addUser");
        model.put("error", error);
        return new ModelAndView("ajax_foo", model);
    }

    public ModelAndView deleteUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String error = "";
        HashMap<String, Object> model = new HashMap<String, Object>();
        try {
            Long userId = Long.parseLong(request.getParameter("userId"));
            User user = userService.getById(userId);
            Long projectId = Long.parseLong(request.getParameter("projectId"));
            Project project = projectService.getById(projectId, true);
            project.getUsers().remove(user);
            projectService.update(project);
        } catch (Exception e) {
            e.printStackTrace();
            error = "Error:Can't delete user";
        }

        model.put("method", "deleteUser");
        model.put("error", error);
        return new ModelAndView("ajax_foo", model);
    }

    public ModelAndView getDetails(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String error = "";
        HashMap<String, Object> model = new HashMap<String, Object>();
        try {
            String target = request.getParameter("target");
            if (target == null) error = "Error:cant get report target";

            if (target.equals("user")){
                 List<User> users = userService.getAll();
                 model.put("users", users);
            } else if (target.equals("resource")){
                List<Resource> resources = resourceService.getAll();
                model.put("resources", resources);
            } else if (target.equals("host")){
                List<Host> hosts = hostService.getAll();
                model.put("hosts", hosts);
            }

        } catch (Exception e) {
            e.printStackTrace();
            error = "Error:Can't prepare report";
        }
        model.put("method", "getDetails");
        model.put("error", error);
        return new ModelAndView("ajax_foo", model);
    }


}
